from django_redis import get_redis_connection
from django.core.exceptions import ValidationError


class BootStrapForm:

    bootstrap_class_exclude = []

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            if name in self.bootstrap_class_exclude:
                continue
            # print(name)  # 字段的名称，比如：username
            field.widget.attrs = {'class': 'form-control', 'placeholder': f'请输入{field.label}'}
            # field.error_messages = {'required': '{}不能为空'.format(field.label), }

    def clean_code(self):
        code = self.cleaned_data.get('code')
        mobile_phone = self.cleaned_data.get('mobile_phone')
        # 手机号不存在，则验证码无需再校验
        if not mobile_phone:
            return code

        conn = get_redis_connection('default')
        ret = conn.get(mobile_phone)
        if not ret:
            raise ValidationError('验证码失效或未发送，请重新发送')
        if code.strip() != ret.decode('utf-8'):
            raise ValidationError('验证码错误，请重新输入')
        return code
